// import { useState } from 'react'
// import { useReducer } from 'react'
import ReactDOM from "react-dom";
let state = [];
let setters = [];
let stateIndex = 0;

function createSetter(index) {
  return function (newState) {
    state[index] = newState;
    render();
  };
}

function useState(initialState) {
  state[stateIndex] = state[stateIndex] ? state[stateIndex] : initialState;
  setters.push(createSetter(stateIndex));
  let value = state[stateIndex];
  let setter = setters[stateIndex];
  stateIndex++;
  return [value, setter];
}

function render() {
  stateIndex = 0;
  effectIndex = 0;
  ReactDOM.render(<App />, document.getElementById("root"));
}

// 上一次的依赖值
let prevDepsAry = [];
let effectIndex = 0;

function useReducer(reducer, initialState) {
  const [state, setState] = useState(initialState);
  function dispatch(action) {
    const newState = reducer(state, action);
    setState(newState);
  }
  return [state, dispatch];
}

function App() {
  function reducer(state, action) {
    switch (action.type) {
      case "increment":
        return state + 1;
      case "decrement":
        return state - 1;
      default:
        return state;
    }
  }
  const [cnt, dispatch] = useReducer(reducer, 0);

  return (
    <div>
      <div>
        <button onClick={() => dispatch({ type: "increment" })}> +1 </button>
        <span>{cnt}</span>
        <button onClick={() => dispatch({ type: "decrement" })}> -1 </button>
      </div>
    </div>
  );
}

export default App;
